package com.guomei.controller.exam;

import com.guomei.bean.exam.IsPassDTO;
import com.guomei.bean.exam.domain.ExamAnswer;
import com.guomei.mapper.UserMapper;
import com.guomei.mapper.curse.ExamMapper;
import com.guomei.service.exam.ExamAnswerService;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * 考试答卷控制器
 */
@RestController
@RequestMapping("/api1/examAnswer")
@Slf4j
public class ExamAnswerController {
    @Autowired
    private ExamAnswerService examAnswerService;

    /**
     * 获取答卷信息
     * @return 答卷列表
     */
    @PostMapping("/select")
    public Result<?> getAllAnswers(@RequestBody ExamAnswer examAnswer) {
        log.info("获取答卷信息");
        try {
            if (examAnswer == null || examAnswer.getPageNum() == null || examAnswer.getPageSize() == null) {
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (examAnswer.getPageNum() <= 0 || examAnswer.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            return examAnswerService.getByCondition(examAnswer);
        } catch (Exception e) {
            log.info("获取答卷信息失败", e);
            return Result.fail("获取答卷信息失败");
        }
    }

    /**
     * 获取用户+答卷判断是否通过
     * @return 列表
     */
    @PostMapping("/selectIs")
    public Result<?> selectIs(@Valid @RequestBody List<IsPassDTO> isPassDTOList, BindingResult result) {
        log.info("获取用户+答卷判断是否通过入参", isPassDTOList);
        //实体类注解参数校验
        Result<?> commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            return examAnswerService.selectIs(isPassDTOList);
        } catch (Exception e) {
            log.info("获取用户+答卷判断是否通过失败", e);
            return Result.fail("获取用户+答卷判断是否通过失败");
        }
    }

    /**
     * 根据ID获取答卷详情
     * @param id 答卷ID
     * @return 答卷详情
     */
    @GetMapping("/detail/{id}")
    public Result<?> getAnswerDetail(@PathVariable Long id) {
        log.info("获取答卷详情，ID：{}", id);
        try {
            if (id == null) {
                return Result.fail("答卷ID不能为空");
            }
            return examAnswerService.getAnswerDetail(id);
        } catch (Exception e) {
            log.info("获取答卷详情失败", e);
            return Result.fail("获取答卷详情失败");
        }
    }

    /**
     * 开始考试
     * @param examId 考试ID
     * @param enrollId 报名ID
     * @param userId 用户ID
     * @return 开始结果
     */
    @PostMapping("/start/{examId}/{enrollId}/{userId}")
    public Result<?> startExam(@PathVariable Long examId, @PathVariable Long enrollId, @PathVariable Long userId) {
        log.info("开始考试，考试ID：{}，报名ID：{}，用户ID：{}", examId, enrollId, userId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            if (enrollId == null) {
                return Result.fail("报名ID不能为空");
            }
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            return examAnswerService.startExam(examId, enrollId, userId);
        } catch (Exception e) {
            log.info("开始考试失败", e);
            return Result.fail("开始考试失败");
        }
    }

    /**
     * 提交答卷
     * @param answerId 答卷ID
     * @param userId 用户ID
     * @return 提交结果
     */
    @PostMapping("/submit/{answerId}/{userId}")
    public Result<?> submitAnswer(@PathVariable Long answerId, @PathVariable Long userId) {
        log.info("提交答卷，答卷ID：{}，用户ID：{}", answerId, userId);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            return examAnswerService.submitAnswer(answerId, userId);
        } catch (Exception e) {
            log.info("提交答卷失败", e);
            return Result.fail("提交答卷失败");
        }
    }

    /**
     * 审核答卷
     * @param answerId 答卷ID
     * @param reviewUserId 审核人ID
     * @param reviewResult 审核结果
     * @param reviewRemark 审核备注
     * @return 审核结果
     */
    @PostMapping("/review/{answerId}/{reviewUserId}/{reviewResult}")
    public Result<?> reviewAnswer(@PathVariable Long answerId, @PathVariable Long reviewUserId, 
                                 @PathVariable Short reviewResult, @RequestParam(required = false) String reviewRemark) {
        log.info("审核答卷，答卷ID：{}，审核人ID：{}，审核结果：{}", answerId, reviewUserId, reviewResult);
        try {
            if (answerId == null) {
                return Result.fail("答卷ID不能为空");
            }
            if (reviewUserId == null) {
                return Result.fail("审核人ID不能为空");
            }
            if (reviewResult == null) {
                return Result.fail("审核结果不能为空");
            }
            return examAnswerService.reviewAnswer(answerId, reviewUserId, reviewResult, reviewRemark);
        } catch (Exception e) {
            log.info("审核答卷失败", e);
            return Result.fail("审核答卷失败");
        }
    }

    /**
     * 主观题评分审核（批量）
     */
    @PostMapping("/review/subjective")
    public Result<?> reviewSubjective(@RequestBody com.guomei.bean.curse.AnswerReviewDTO reviewDTO) {
        log.info("主观题评分审核，请求：{}", reviewDTO);
        try {
            return examAnswerService.reviewSubjectiveScores(reviewDTO);
        } catch (Exception e) {
            log.info("主观题评分审核失败", e);
            return Result.fail("审核失败");
        }
    }

    /**
     * 根据考试ID获取答卷列表
     * @param examId 考试ID
     * @return 答卷列表
     */
    @GetMapping("/exam/{examId}")
    public Result<?> getAnswersByExamId(@PathVariable Long examId) {
        log.info("根据考试ID获取答卷列表，考试ID：{}", examId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            List<ExamAnswer> answers = examAnswerService.getByExamId(examId);
            return Result.success(answers);
        } catch (Exception e) {
            log.info("根据考试ID获取答卷列表失败", e);
            return Result.fail("获取答卷列表失败");
        }
    }

    /**
     * 根据用户ID获取答卷列表
     * @param userId 用户ID
     * @return 答卷列表
     */
    @GetMapping("/user/{userId}")
    public Result<?> getAnswersByUserId(@PathVariable Long userId) {
        log.info("根据用户ID获取答卷列表，用户ID：{}", userId);
        try {
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            List<ExamAnswer> answers = examAnswerService.getByUserId(userId);
            return Result.success(answers);
        } catch (Exception e) {
            log.info("根据用户ID获取答卷列表失败", e);
            return Result.fail("获取答卷列表失败");
        }
    }

    /**
     * 根据报名ID获取答卷列表
     * @param enrollId 报名ID
     * @return 答卷列表
     */
    @GetMapping("/enroll/{enrollId}")
    public Result<?> getAnswersByEnrollId(@PathVariable Long enrollId) {
        log.info("根据报名ID获取答卷列表，报名ID：{}", enrollId);
        try {
            if (enrollId == null) {
                return Result.fail("报名ID不能为空");
            }
            List<ExamAnswer> answers = examAnswerService.getByEnrollId(enrollId);
            return Result.success(answers);
        } catch (Exception e) {
            log.info("根据报名ID获取答卷列表失败", e);
            return Result.fail("获取答卷列表失败");
        }
    }

    /**
     * 根据状态获取答卷列表
     * @param status 状态
     * @return 答卷列表
     */
    @GetMapping("/status/{status}")
    public Result<?> getAnswersByStatus(@PathVariable Short status) {
        log.info("根据状态获取答卷列表，状态：{}", status);
        try {
            if (status == null) {
                return Result.fail("状态不能为空");
            }
            List<ExamAnswer> answers = examAnswerService.getByStatus(status);
            return Result.success(answers);
        } catch (Exception e) {
            log.info("根据状态获取答卷列表失败", e);
            return Result.fail("获取答卷列表失败");
        }
    }

    /**
     * 根据审核人ID获取答卷列表
     * @param reviewUserId 审核人ID
     * @return 答卷列表
     */
    @GetMapping("/reviewer/{reviewUserId}")
    public Result<?> getAnswersByReviewUserId(@PathVariable Long reviewUserId) {
        log.info("根据审核人ID获取答卷列表，审核人ID：{}", reviewUserId);
        try {
            if (reviewUserId == null) {
                return Result.fail("审核人ID不能为空");
            }
            List<ExamAnswer> answers = examAnswerService.getByReviewUserId(reviewUserId);
            return Result.success(answers);
        } catch (Exception e) {
            log.info("根据审核人ID获取答卷列表失败", e);
            return Result.fail("获取答卷列表失败");
        }
    }

    /**
     * 根据审核结果获取答卷列表
     * @param reviewResult 审核结果
     * @return 答卷列表
     */
    @GetMapping("/result/{reviewResult}")
    public Result<?> getAnswersByReviewResult(@PathVariable Short reviewResult) {
        log.info("根据审核结果获取答卷列表，审核结果：{}", reviewResult);
        try {
            if (reviewResult == null) {
                return Result.fail("审核结果不能为空");
            }
            List<ExamAnswer> answers = examAnswerService.getByReviewResult(reviewResult);
            return Result.success(answers);
        } catch (Exception e) {
            log.info("根据审核结果获取答卷列表失败", e);
            return Result.fail("获取答卷列表失败");
        }
    }

    /**
     * 统计用户答卷数量
     * @param userId 用户ID
     * @return 答卷数量
     */
    @GetMapping("/count/user/{userId}")
    public Result<?> countByUserId(@PathVariable Long userId) {
        log.info("统计用户答卷数量，用户ID：{}", userId);
        try {
            if (userId == null) {
                return Result.fail("用户ID不能为空");
            }
            int count = examAnswerService.countByUserId(userId);
            return Result.success(count);
        } catch (Exception e) {
            log.info("统计用户答卷数量失败", e);
            return Result.fail("统计失败");
        }
    }

    /**
     * 统计考试答卷数量
     * @param examId 考试ID
     * @return 答卷数量
     */
    @GetMapping("/count/exam/{examId}")
    public Result<?> countByExamId(@PathVariable Long examId) {
        log.info("统计考试答卷数量，考试ID：{}", examId);
        try {
            if (examId == null) {
                return Result.fail("考试ID不能为空");
            }
            int count = examAnswerService.countByExamId(examId);
            return Result.success(count);
        } catch (Exception e) {
            log.info("统计考试答卷数量失败", e);
            return Result.fail("统计失败");
        }
    }

    /**
     * 统计待审核答卷数量
     * @param status 状态
     * @return 答卷数量
     */
    @GetMapping("/count/status/{status}")
    public Result<?> countByStatus(@PathVariable Short status) {
        log.info("统计待审核答卷数量，状态：{}", status);
        try {
            if (status == null) {
                return Result.fail("状态不能为空");
            }
            int count = examAnswerService.countByStatus(status);
            return Result.success(count);
        } catch (Exception e) {
            log.info("统计待审核答卷数量失败", e);
            return Result.fail("统计失败");
        }
    }
}
